import pymysql


# 创建工具类
class DBTools(object):
    # 创建静态方法
    @staticmethod
    # 建立连接
    def __db_connect():
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2022", database="ihrm",
                               charset="utf8")
        # 返回连接的对象
        return conn

    # 数据库查询，sql代表用户指定的 查询语句
    @staticmethod
    def query_one(sql):
        conn = None
        cursor = None

        # 执行sql语句，获取结果集
        try:
            # 创建连接
            conn = DBTools.__db_connect()
            # 创建游标
            cursor = conn.cursor()

            # 执行 sql 语句
            cursor.execute(sql)
            # 获取第一条数据
            ret = cursor.fetchone()
            # 返回查询得一条记录
            return ret
        except Exception as err:
            print("出错了", err)
        finally:
            # 5. 关闭游标
            cursor.close()
            # 6. 关闭连接
            conn.close()

    def query_many(self, sql):
        pass
        # 执行sql语句，获取结果集
        # 返回查询的多条记录

    # 数据库 增删改
    @staticmethod
    def db_idu(sql):
        conn = None
        cursor = None
        try:
            # 2. 创建连接
            conn = DBTools.__db_connect()
            # 3. 创建游标
            cursor = conn.cursor()

            # 4. 执行 sql 语句
            cursor.execute(sql)
            # 提交事务
            conn.commit()
            print("数据库操作完成")
        except Exception as err:
            print("数据库操作异常", err)
            # 回滚事务
            conn.rollback()
        finally:
            # 5. 关闭游标
            cursor.close()
            # 6. 关闭连接
            conn.close()


if __name__ == '__main__':
    # ret = DBTools.query_one("select * from bs_user where id = '1063705989926227968'; ")
    # print(ret)
    ret = DBTools.db_idu("delete from bs_user where mobile='13835465457';")
    print(ret)
